package com.mice.game.trigger
{
	import com.mice.game.core.Actor;
	import com.mice.game.core.Fighter;
	
	import flash.utils.Dictionary;

	/**
	 * fight探测器.用来探测fighter攻击,前进
	 */	
	public class FighterTrigger{
		private static var _instance:FighterTrigger;
		
		/**
		 * 红方战斗单位
		 */		
		private var _redFighterList:Array = new Array();
		
		/**
		 * 蓝方战斗单位
		 */		
		private var _blueFighterList:Array = new Array();
		
		public function FighterTrigger(){}
		
		public static function get instance():FighterTrigger{
			if (_instance == null)
				_instance = new FighterTrigger();
			return _instance;
		}
		
		public function reset():void{
			_redFighterList = new Array();
			_blueFighterList = new Array();
		}
		
		/**
		 * 添加红方战士
		 */		
		public function addRedFighter(fighter:Fighter):void{
			_redFighterList.push(fighter);
		}
		
		/**
		 * 添加蓝方战士
		 */		
		public function addBlueFighter(fighter:Fighter):void{
			_blueFighterList.push(fighter);
		}
		
		/**
		 * 每*帧运行
		 */		
		public function update():void{
			updateTeamRun(_redFighterList);
			updateTeamRun(_blueFighterList);
			
			updateTeamFight(_redFighterList, _blueFighterList);
		}
		
		/**
		 * 更新前进状态,位置
		 */		
		private function updateTeamRun(team:Array):void{
			for each (var actor:Fighter in team){
				actor.step();
			}
		}
		
		/**
		 * 检测两个中的战斗单位的行为
		 * 战斗/前进/死亡
		 * @param team1 进攻方
		 * @param team2 挨打方
		 */		
		private function updateTeamFight(team1:Array, team2:Array):void{
			var fighter1:Fighter;
			var fighter2:Fighter;
			for (var i:int = (team1.length - 1); i >= 0; i--){
				fighter1 = team1[i] as Fighter;
				if (fighter1.isAttack)continue;
				if (fighter1.isDead){
					team1.splice(i, 1);
					continue;
				}
				
				for (var j:int = (team2.length - 1); j >= 0; j--){
					fighter2 = team2[j] as Fighter;
					if (fighter2.isDead){
						team2.splice(j, 1);
						continue;
					}
					
					if(fighter1.testAttackRange(fighter2)){
						fighter1.attack(fighter2);
						//这里不需要判断fighter2是否死亡
						//如果死亡,这是fight1的动画还没播放完毕,所以不能立刻改成行走动画
						//要在下次更新中,前进
						DamageTrigger.instance.addAttacker(fighter1);
					}
					
					if (fighter2.isDead)continue;
					if(fighter2.testAttackRange(fighter1)){
						fighter2.attack(fighter1);
						DamageTrigger.instance.addAttacker(fighter2);
					}
				}
			}
		}
	}
}